package com.woniuxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.dto.MenusDto;
import com.woniuxy.dto.RolesAndMenusDto;
import com.woniuxy.dto.UserRelatedDto.UserTableDetails;
import com.woniuxy.dto.goodsGeneralAndSmallAndBrand.GoodsSmallerDto;
import com.woniuxy.entity.MenuTable;
import com.woniuxy.entity.RoleMenu;
import com.woniuxy.mapper.MenuTableMapper;
import com.woniuxy.service.MenuTableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.RoleMenuService;
import com.woniuxy.util.WoniuBeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zcx, ftl, gr, rhs
 * @since 2021-12-31
 */
@Service
public class MenuTableServiceImpl extends ServiceImpl<MenuTableMapper, MenuTable> implements MenuTableService {


    //修改做redis保存
    @Resource
    private RedisTemplate<String, List<MenusDto>> rt;
    @Resource
    private RoleMenuService rms;

    @Override
    public List<MenusDto> listMenusByUserId() {
        //获取保存的登录信息
        UserTableDetails utd = ((UserTableDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal());


        List<MenusDto> range = rt.opsForValue().get("pawn:menu:userId" + utd.getUserId());
        List<MenusDto> list = new ArrayList<>();


        if (null == range || range.size() <= 0) {

            //获取当前用户可以看到的所有菜单
            QueryWrapper<MenuTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(" t1.user_id ", utd.getUserId());
            queryWrapper.eq(" t4.menu_del ", 0);
            //锁定表不能查看但是是真实存在分配属性的
            queryWrapper.eq(" t4.menu_status ", 0);
            List<MenuTable> menuTables = this.baseMapper.listMenusByKey(queryWrapper);
            List<MenusDto> mds = new ArrayList<>();
            HashMap<Integer, MenusDto> maps = new HashMap<>();
            for (MenuTable menuTable : menuTables) {
                //这样写法可以让指针相同
                MenusDto dto = WoniuBeanUtils.copyObject(menuTable, MenusDto.class);
                if (dto.getMenuPid() == 0) mds.add(dto);
                maps.put(dto.getMenuId(), dto);
            }

//        循环添加子节点
            for (MenusDto md : maps.values()) {
                MenusDto dto = maps.get(md.getMenuPid());
                if (dto != null) {
                    dto.setListMenus(dto.getListMenus() == null ? new ArrayList<MenusDto>() : dto.getListMenus());
                    dto.getListMenus().add(md);
                }

            }

//            return mds;
//                并且放入redis
            rt.opsForValue().set("pawn:menu:userId" + utd.getUserId(), WoniuBeanUtils.copyList(mds, MenusDto.class));
            rt.expire("pawn:menu:userId" + utd.getUserId(), 30, TimeUnit.MINUTES);

            list = mds;
        }else {
            list = WoniuBeanUtils.copyList(range, MenusDto.class);
        }
        return list;


    }

    @Override
    public RolesAndMenusDto listMenusByRoleId(String roleId) {
        List<MenuTable> listMenu = list(new QueryWrapper<MenuTable>().eq("menu_del", 0));

        List<MenusDto> mds = new ArrayList<>();

        RolesAndMenusDto roleAndMenusDto = new RolesAndMenusDto();

        Map<Integer, MenusDto> maps = new HashMap<>();
        for (MenuTable menu : listMenu) {
            //这样写法可以让指针相同
            MenusDto dto = WoniuBeanUtils.copyObject(menu, MenusDto.class);
            if (menu.getMenuPid() == 0) mds.add(dto);
            maps.put(menu.getMenuId(), dto);
        }

//        循环添加子节点
        for (MenusDto md : maps.values()) {
            MenusDto dto = maps.get(md.getMenuPid());
            if (dto != null) {
                dto.setListMenus(dto.getListMenus() == null ? new ArrayList<MenusDto>() : dto.getListMenus());
                dto.getListMenus().add(md);
            }

        }

        roleAndMenusDto.setList(mds);

        List<RoleMenu> menus = rms.list(new QueryWrapper<RoleMenu>().eq("role_id", roleId));

        if (menus == null || menus.size() <= 0) roleAndMenusDto.setIds(new ArrayList<>());
        else {
            List<Integer> ids = menus.stream().map(
                    id -> id.getMenuId()
            ).collect(Collectors.toList());

            ids = list(new QueryWrapper<MenuTable>().eq("menu_sub", 1).in("menu_id", ids)).stream().map(
                    menu -> menu.getMenuId()
            ).collect(Collectors.toList());
            roleAndMenusDto.setIds(ids);
        }
        return roleAndMenusDto;
    }
}
